using System;
using UnityEngine;
using UnityEngine.InputSystem;

namespace DTFramework.Entity
{
    public abstract class AttachTagBase : MonoBehaviour
    {
        [Header("[AttachTagBase]")]
        [SerializeField] protected Collider m_ClickCollider;
        [SerializeField] float m_ScaleFactor = 0.01f;
        [SerializeField] float m_RayDistance = 1500f;

        private Vector3 _initScale;
        public event Action OnClickEvent;
        protected InputManager _inputManager;
        protected Camera _mainCamera;

        public bool IsClickHandle
        {
            set { if (m_ClickCollider) m_ClickCollider.enabled = value; }
        }
        protected virtual void Awake()
        {
            _initScale = transform.localScale;
        }
        protected virtual void Update()
        {
            UpdateScaleText();
        }

        /// <summary>
        /// 显示
        /// </summary>
        public virtual void OnShow()
        {
            _mainCamera = GameEntry.CameraControl?.CameraUtil;
            _inputManager = GameEntry.CameraControl?.InputManager;
            if (_inputManager != null)
                _inputManager.CameraControl.Mouse_Move.started += OnRaycastToClick;
        }
        /// <summary>
        /// 隐藏
        /// </summary>
        public virtual void OnHide()
        {
            if (_inputManager != null)
                _inputManager.CameraControl.Mouse_Move.started -= OnRaycastToClick;
        }
        // 获取当前图标点击事件
        private void OnRaycastToClick(InputAction.CallbackContext context)
        {
            if (_mainCamera == null) throw new Exception("CameraControl.CameraUtil is null");

            var mousePos = Mouse.current.position.ReadValue();
            var ray = _mainCamera.ScreenPointToRay(mousePos);
            if (m_ClickCollider.Raycast(ray, out RaycastHit hit, m_RayDistance))
            {
                OnClickEvent?.Invoke();
            }
        }


        //更新大小
        private void UpdateScaleText()
        {
            if (!_mainCamera) return;
            if (m_ScaleFactor == 0) return;
            float distance = Vector3.Distance(_mainCamera.transform.position, transform.position);
            float scale = distance * m_ScaleFactor;
            transform.localScale = _initScale * Mathf.Clamp(scale, 1, 100);
        }
    }
}